package javacommon.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javacommon.base.LoadConfig;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


public class Common {

	
	public static final String ATTACH_IMG_SRC = "images/attach/";
	// TODO lx add isMobileNo
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public static String md5(String in) {
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance("MD5");
			digest.reset();
			digest.update(in.getBytes());
			byte[] a = digest.digest();
			int len = a.length;
			StringBuilder sb = new StringBuilder(len << 1);
			for (int i = 0; i < len; i++) {
				sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
				sb.append(Character.forDigit(a[i] & 0x0f, 16));
			}
			// return Base64.encode(a);
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String HashEncryptString(String originalPwd,
			String lastTwochar) {
		String Key = lastTwochar;

		String base64Result = md5(originalPwd + Key);
		if (base64Result.endsWith("=="))
			return base64Result.replace("==", Key);
		return base64Result + Key;
	}

	public static String getFilename(String url) {
		String parts[] = url.split("/");
		String filename = parts[parts.length - 1];// .lastIndexOf("/")
		return filename;
	}

//	public static void addImRoster(String username, Contact newEr,
//			List<Contact> friends, LoadConfig c) {
//		try {
//			Class.forName("com.mysql.jdbc.Driver").newInstance();
//		} catch (InstantiationException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IllegalAccessException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (ClassNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		Connection con;
//		try {
//			con = java.sql.DriverManager.getConnection(c.getURL(),
//					c.getUserName(), c.getPassWord()
//			// "jdbc:mysql://127.0.0.1:3306/xmppserver?useUnicode=true&amp;characterEncoding=UTF-8",
//			// "root", "dongliang,325"
//					);
//			Statement stmt = con.createStatement();
//			if (friends != null) {
//				int maxId = 0;
//				ResultSet rst = stmt
//						.executeQuery("select max(rosterID) as rosterID from ofRoster");
//				while (rst.next()) {
//					maxId = rst.getInt("rosterID");
//				}
//				// 关闭连接、释放资源
//				rst.close();
//
//				for (Contact contact : friends) {
//					if (contact.getMessagerid() != null
//							&& contact.getMessagerid().equals(
//									newEr.getMessagerid()) == false) {
//						String friendJid = contact.getMessagerid();
//						String friendUsername = friendJid.split("@")[0];
//						boolean alreadyFriends = false;
//						ResultSet fd = stmt
//								.executeQuery("select username,jid from ofRoster where username='"
//										+ username
//										+ "' and jid='"
//										+ contact.getMessagerid() + "'");
//						if (fd.next()) {
//							alreadyFriends = true;
//						}
//						// 关闭连接、释放资源
//						fd.close();
//						if (!alreadyFriends) {
//							maxId++;
//							String sql = "insert into ofRoster(rosterID,username, jid, sub, ask, recv, nick) values "
//									+ "("
//									+ maxId
//									+ ",'"
//									+ username
//									+ "', '"
//									+ contact.getMessagerid() + "',0,-1,-1,'')";
//							stmt.executeUpdate(sql);
//
//							maxId++;
//							String sql2 = "insert into ofRoster(rosterID,username, jid, sub, ask, recv, nick) values "
//									+ "("
//									+ maxId
//									+ ",'"
//									+ friendUsername
//									+ "', '"
//									+ newEr.getMessagerid()
//									+ "',0,-1,-1,'')";
//							stmt.executeUpdate(sql2);
//						}
//					}
//				}
//			}
//			stmt.close();
//			con.close();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//	}

	public static void addImUser(String username, String pwd, LoadConfig c) {
		/*
		 * http://localhost:9090/plugins/userService/userservice?type=add
		 * &secret
		 * =bigsecret&username=kafka&password=drowssap&name=franz&email=franz
		 * 
		 * @kafka.com
		 */
		String urlString = "http://" + c.getImServer()
				+ ":9090/plugins/userService/userservice?type=add" + "&secret="
				+ c.getImSecret() + "&username=" + username + "&password="
				+ pwd + "";
		sendImUserRequest(urlString);
	}

	public static void deleteImUser(String username, LoadConfig c) {
		// http://example.com:9090/plugins/userService/userservice?type=delete&secret=bigsecret&username=kafka
		String urlString = "http://" + c.getImServer()
				+ ":9090/plugins/userService/userservice?type=delete&secret="
				+ c.getImSecret() + "&username=" + username;
		sendImUserRequest(urlString);
	}

	public static void updateImUser(String username, String pwd, LoadConfig c) {
		/*
		 * http://example.com:9090/plugins/userService/userservice?
		 * type=update&secret
		 * =bigsecret&username=kafka&password=drowssap&name=franz
		 * &email=beetle@kafka.com
		 */
		String urlString = "http://" + c.getImServer()
				+ ":9090/plugins/userService/userservice?type=update"
				+ "&secret=" + c.getImSecret() + "&username=" + username
				+ "&password=" + pwd + "";
		sendImUserRequest(urlString);
	}

	private static void sendImUserRequest(String urlString) {
		URL url;
		try {
			url = new URL(urlString);
			HttpURLConnection url_con = (HttpURLConnection) url
					.openConnection();
			url_con.setDoOutput(true);
			url_con.setRequestMethod("GET");

			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
			InputStream in = url_con.getInputStream();

			StringBuilder temp = new StringBuilder();

			BufferedReader rd = new BufferedReader(new InputStreamReader(in));
			while (rd.read() != -1) {
				temp.append(rd.readLine());
			}
			System.out.println(new String(temp));

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Date toDate(String dateStr) throws ParseException{
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = fm.parse(dateStr);
		return date;
	}

	public static String getCurrentDate(){
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = fm.format(calendar.getTime());
		return date;
	}
	
	public static Date getCurrentDate2(){
		Calendar calendar = Calendar.getInstance();
		
		return calendar.getTime();
	}
	
	public static String getCurrentDate3(){
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = fm.format(calendar.getTime());
		return date;
	}
	
	public static String getCurrentDate4(){
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
		String date = fm.format(calendar.getTime());
		return date;
	}
	
	public static boolean compareDate(String date1str , String date2str){
		if (date1str == null || date2str == null)
            return false;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date();
        Date date2 = new Date();
		try {
			date1 = sdf.parse(date1str);
			date2 = sdf.parse(date2str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(date1.getTime()>date2.getTime()){
			return true;
		}else{
			return false;
		}
	}
	
	public static int compareDay(String date1str, String date2str)
	{
        if (date1str == null || date2str == null)
            return 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        Date date2 = null;
		try {
			date1 = sdf.parse(date1str);
			date2 = sdf.parse(date2str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
        
        return compareDay(date1, date2);
	}
	
	
	public static int compareDay(java.util.Date date1, java.util.Date date2)
	{
        if (date1 == null || date2 == null)
            return 0;

        long time1 = date1.getTime();
        long time2 = date2.getTime();

        long margin = time1 - time2;

        /* 转化成天数 */
        int ret = (int)Math.floor((double)margin / (1000 * 60 * 60 * 24));

        return ret;
	}
	
	public static boolean checkNum(String str){
		Pattern p = Pattern.compile("^\\d*[1-9]\\d*$");
        Matcher m = p.matcher(str);   
        boolean b = m.matches();   
		return b;
	}
	
	public static boolean checkDate(String str){
		String eL= "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";  
        Pattern p = Pattern.compile(eL);   
        Matcher m = p.matcher(str);   
        boolean b = m.matches();  
        return b;
	}
	
	public static boolean checkTime(String time){
		String eL= "^([0-1]\\d|[2][0-3])\\:([0-5]\\d)$";  
        Pattern p = Pattern.compile(eL);
        Matcher m = p.matcher(time);   
        boolean b = m.matches();  
        return b;
	}
	
//	public static List<AttachDto> uploadAttch(MultipartHttpServletRequest multipartRequest,HttpServletRequest request){
//		List<AttachDto> attachList = new ArrayList<AttachDto>();
//		for(String key : multipartRequest.getFileMap().keySet()){
//			MultipartFile multipartFile = multipartRequest.getFileMap().get(key);
//			try {
//				if(multipartFile.getBytes()!=null && multipartFile.getBytes().length>0){
//					String ext = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
//					String currentDate = Common.getCurrentDate3();
//					String attachSrc = Common.ATTACH_IMG_SRC+currentDate+"."+ext;
//					try {
//						File file = new File(request.getSession().getServletContext().getRealPath("/")+attachSrc);
//						OutputStream ot = new FileOutputStream(file);
//						IOUtils.write(multipartFile.getBytes(), ot);
//					} catch (IOException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					AttachDto attachDto = new AttachDto();
//					attachDto.setType(ext);
//					attachDto.setName(FilenameUtils.getBaseName(multipartFile.getOriginalFilename()));
//					attachDto.setUrl(attachSrc);
//					attachList.add(attachDto);
//				}
//			} catch (IOException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
//			
//		}
//		return attachList;
//	}
	
}
